<?php
class Dmf_Template
{
    /**
     * The view
     * 
     * @var Dmf_Resource 
     */
    public $view;
    
    /**
     * The layout
     * 
     * @var Dmf_Layout 
     */
    public $layout;
    
    /**
     * The request
     * 
     * @var Dmf_Request 
     */
    public $request;
    
    /**
     * The layout file
     * 
     * @var string
     */
    public $layout_file;
    
    /**
     * Configuration settings
     * 
     * @var Dmf_Config_Ini|Dmf_Config_Php
     */
    private $_config;
    
    /**
     * Constructor
     * 
     * @param Dmf_Request $request 
     */
    public function __construct( Dmf_Request $request )
    {
        $this->request = $request;
        $this->_config = Dmf_Application::getInstance()->getConfig()->asObject();
    }
    
     /**
     * Prepare the layouts and views and create
     * the neccesarry objects but do not render them. 
     */
    public function preparePage()
    {
        $this->layout = new Dmf_Layout( ( $this->request->getModule() !== null ) ? 'application/modules/%2/layouts/%1.phtml' : 'application/layouts/%1.phtml' );
        
        if ( $this->_config->view->autoload )
        {
            $this->view = new Dmf_View( ( $this->request->getModule() !== null ) ? 'application/modules/%3/views/%1/%2.phtml' : 'application/views/%1/%2.phtml' );
            
            $this->layout->clearViews();
            $this->layout->addView( $this->view );
        }
    }
    
    /**
     * Render the entire page, when false is returned
     * in a controller the page won't be rendered. Also
     * set the correct names according to the request.
     * 
     * @param mixed $result 
     */
    public function renderPage( $result )
    {
        $this->layout->setFile( sgetf( $this->layout->getFile(), array( ( $this->layout_file !== null ) ? $this->layout_file : $this->_config->layout->default, $this->request->getModule() ) ) );
        $this->view->setFile( sgetf( $this->view->getFile(), array( $this->request->getController(), $this->request->getAction(), $this->request->getModule() ) ) );
        
        $this->renderContent( $result );
        
        if ( $result === false || $result !== null )
        {
            return false;
        }
        
        if ( $this->_config->layout->enabled === false || $this->layout_file === false )
        {
            $this->layout->view->render();
        }
        else
        {
            $this->layout->render();
        }
    }
    
    /**
     * Render the content from the controller
     * 
     * @param boolean $result
     * @return type 
     */
    public function renderContent( $result )
    {
        if ( $result !== false && $result !== null )
        {
            echo $result;
            return;
        }
    }
}